<?php
/**
 * Created by PhpStorm.
 * User: 毛文科
 * Date: 2018/8/23 0023
 * Time: 14:08
 */
namespace app\admin\model;
use think\Db;

class ReportModel
{
    /**获取报告的模型
     * @return $this
     */
    static public function getReport(){
        return Db::view('work_report',true)
            ->view('user',['nickname'=>'fasong'],'user.id=work_report.author','left')
//            ->view('user',['user.nickname'=>'jieshou'],'user.id=work_report.recipient','left')
            ->view('company','company_name','company.id=work_report.company_id','left')
            ->view('departmen_table','departmen_name','departmen_table.id=work_report.department_id','left')
            ->json(['picture']);
    }

    /**添加报告
     * @param $data
     * @return int|string
     */
    static public function addReport($data){
        return Db::name('work_report')->json(['picture'])->insert($data);
    }

    /**添加报告,并获取id
     * @param $data
     * @return int|string
     */
    static public function addReportGetId($data){
        return Db::name('work_report')->json(['picture'])->insertGetId($data);
    }

    /**删除报告
     * @param $field
     * @param null $op
     * @param null $condition
     * @return int
     */
    static public function delReport($field, $op = null, $condition = null){
        $sul = Db::connect();
        $reports = $sul->name('work_report')->json(['picture'])->where($field,$op,$condition)->select();
        foreach ($reports as $report){
            if(is_array($report['picture'])){
                foreach ($report['picture'] as $value){
                    if(is_file(config('FileRoot').$value)){
                        unlink(config('FileRoot').$value);
                    }
                }
            }
        }
        return $sul->name('work_report')->where($field,$op,$condition)->delete();
    }

    /**更新报告
     * @param $data
     * @return int|string
     */
    static public function updateReport($data){
        $sul = Db::connect();
        if($data['picture']){
            $report = $sul->name('work_report')->json(['picture'])->where('id',$data['id'])->find();
            if(is_array($report['picture'])){
                foreach ($report['picture'] as $value){
                    if(is_file(config('FileRoot').$value)){
                        unlink(config('FileRoot').$value);
                    }
                }
            }
        }
        return $sul->name('work_report')->json(['picture'])->update($data);
    }
}